<template>
  <!-- 分享二维码 -->
   <div class="shareB1" @click="closeShare" v-show="shareShow == true">
      <div class="shareB">
  <div class="share" >
    <p class="title">{{ shareDate.title }}</p>
    <div class="content">
      <div>
          <img
        class="imgpath"
        v-if="pic=='1'"
        crossOrigin="anonymous"
        :src="imgpath"
        alt=""
      />
        <img :src="shareDate.bg" class="posterBg" />
        <div class="vueBox">
           <vue-qr
          :text="loginUrl"
          :size="200"
          :margin="16"
          whiteMargin="true"
          class="vue-qr-img"
        ></vue-qr>
        <p class="shareTxt"><span>微信扫一扫</span><span>开启0元购</span><span>分享赚佣金</span></p>
        
        </div>
       
      </div>
    </div>
    
    <div class="category" v-if="from1 == 'app'">
      <div class="content1" v-for="(item, index) in category" :key="index" @click.stop="sharePic(item.id,item.number)">
        <img :src="item.pic" alt="" />
        <span>{{ item.name }}</span>
      </div>
       <div class="content1 copy"  @click="copy()" :data-clipboard-text="loginUrl">
        <img src="@assets/images/cutPrice/copy.png" alt="" />
        <span>复制链接</span>
      </div>
    </div>
    <div v-else class="h5">长按保存图片</div>
  </div>
   </div>
    </div>
</template>

<script>
import html2canvas from "html2canvas";
import vueQr from "vue-qr";
import lrz from "lrz";
import { VUE_APP_WS_URL } from "@utils/index";
import cbct from "@common/base.js";
import qs from "qs";
import http from "@common/http.js";
import axios from "axios";
import cookie from "@utils/store/cookie";
import ClipboardJS from "clipboard";
import shareMsg from "@common/shareConfig.js";
export default {
  name: "sharePoster",
  props: {
    from1: {
      type: String,
      default: ""
    },
    category: {
      type: Array,
      default: []
    },
    shareShow: {
      type: Boolean,
      default: false
    },
    shareDate: {
      type: Object,
      default() {
        return {
          bg: undefined,
          title: ""
        };
      }
    }
  },
  data() {
    return {
      loginUrl:'',
      imgpath: "",
      shareImg: "",
      pic:'0'
    };
  },
  components: {
    vueQr
  },
  methods: {
    isShare1() {
      this.shareShow = false;
      this.$emit('isShare', this.shareShow)
    },
    // base64转二进制流
    tofileobj(data) {
      const binary = atob(data.split(",")[1]);
      const mime = data.split(",")[0].match(/:(.*?);/)[1];
      const array = [];
      for (let i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
      }
      const fileData = new Blob([new Uint8Array(array)], {
        type: mime
      });

      const file = new File([fileData], `${new Date().getTime()}.png`, {
        type: mime
      });
      return file;
    },
    // 复制兑换码
    copy() {
      console.log(this.loginUrl)
      var Url =this.loginUrl
      let clipboard = new ClipboardJS(".copy", {
        text: () => {
          return `${Url}`;
        }
      });
      clipboard.on("success", () => {
        this.$dialog.success("复制成功");
         this.closeShare()
      });
    },
    sharePic(actionType,isshare){
      let jumptype = isshare;
      if (jumptype == '1') {
        //单独分享
        shareMsg.singleShare(
          "app",
          "1",
          "",
          "",
          "",
          this.shareImg,
          "",
          actionType
        );
      } else if (jumptype == '2') {
        
        //本地保存
        shareMsg.onAction("app", actionType, {
          shareImage: this.shareImg
        });
      }
        this.closeShare()
         
    },
    getimg() {
      this.loginUrl = `${VUE_APP_WS_URL}cutPrice/cutPriceIndex`;
      if(cookie.get('cutUid')){
        this.loginUrl = `${VUE_APP_WS_URL}cutPrice/cutPriceIndex?shareUserId=`+cookie.get('cutUid')
      }
     console.log(this.loginUrl)
      if(this.shareImg==''){
       this.$dialog.loading.open("图片生成中");
      window.pageYOffset = 0;
      document.documentElement.scrollTop = 0;
      document.body.scrollTop = 0;
      let img = new Image();
      img.src = $(".posterBg").attr("src");
      //img.src = document.querySelector('.bg').src;
      console.log(document.querySelector('.content').offsetWidth)
      console.log( $(".content").width())
      console.log( $(".content").height())
      img.onload = () => {
        setTimeout(() => {
          var self = this;
          html2canvas(document.querySelector(".content"), {
            taintTest: true, //在渲染前测试图片(没整明白有啥用)
            useCORS: true, //使用跨域(当allowTaint为true时这段代码没什么用)
            width: $(".content").width(), //设置canvas尺寸与所截图尺寸相同，防止白边
            height: $(".content").height() //防止白边
          }).then(canvas => {
            this.imgpath = canvas.toDataURL("image/png", 1.0); //将图片转为base64, 0-1 表示清晰度
            //图片压缩
            // lrz(this.imgpath).then(rst => {
              let form = this.tofileobj(this.imgpath);
              console.log("form", form);
              let fd = new FormData();
              fd.append("name", form);
              fd.append("type", "image");
              http.post(cbct.https()+'/h5/upload-image',fd, qs.stringify({})).then((response)=>{
                  if (response.c == cbct.code.successRes) {
                    console.log(response.d.url, "response.d.url");
                    self.shareImg = response.d.url; //给客户端传的图片
                    if(self.from1!='app'){
                       self.pic =1
                    }
                    this.$dialog.loading.close();
                  } 
                }).catch(error => {this.closeShare();this.$dialog.loading.close();});
            });
          // });
        }, 2000);
      }
           
       }
    },
    //二维码base64地址，异步回调
    callback(data, qid) {
      let obj = { data, qid };
      this.dataUrl.push(obj);
    },
    //关闭海报
    closeShare() {
      this.shareShow = false;
      this.isShare1()
    }
  },
  mounted() {
    var self = this;
     axios.defaults.headers = {
        'Content-Type':'application/x-www-form-urlencoded',
      };
     axios.post(cbct.https()+'/admin/time', {  
      }).then(function (response) {
        if(response.data.c == cbct.code.successRes){
          var timing = response.data.d.time - Date.parse(new Date());            
          cookie.set('timing',timing);
          // self.getimg();
        }
      })
    if (this.from1 != "app") {
      console.log("this==" + this.from1);
      // this.getimg();
    }
    
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
//分享海报
.shareB1 {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  background: rgba(0, 0, 0, 0.5);
  z-index: 120;
  .shareB {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: auto;
    background: #f9f9f9;
    border-radius: 0.4rem 0.4rem 0 0;
  }
}
.share {
  width: 100%;
  height: auto;
  overflow: hidden;
  text-align: center;
  .title {
    height: 1.14rem;
    font-size: 0.32rem;
    color: #000;
    font-weight: 500;
    line-height: 1.14rem;
  }
  .content {
    width: 4.92rem;
    height: 7.14rem;
    overflow: hidden;
    border-radius: 0.12rem;
    margin: 0 auto;
    position: relative;
    .imgpath{
       width: 100%;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 999;
    }
    .posterBg {
      width: 100%;
      position: absolute;
      top: 0;
      left: 0;
    }
    .vueBox{
      position: absolute;
      left: .86rem;
      bottom: .4rem;
      .vue-qr-img {
        width: 1.38rem;
        height: 1.42rem;
        float: left;
      }
      .shareTxt{
        float: left;
        width: 1.6rem;
        margin: .2rem 0 0 .4rem;
          span{
          display:block;
          width: 1.6rem;
          font-size:.24rem;
          color: rgba(255, 255, 255, .9);
          // line-height: .34rem;
          // margin: .2rem 0 0 .4rem;
          text-align: left;
          font-weight: 500;
          letter-spacing:.02rem ;
        }
      }
      
    }
   
  }
  .category {
    height: 2.24rem;
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    border-top: 0.02rem solid rgba(0, 0, 0, 0.1);
    align-items: center;
    margin-top: 0.52rem auto 0;
    padding: 0 .25rem;
    box-sizing: border-box;
    .content1 {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 20%;
      img {
        width: 0.92rem;
        margin-bottom: .04rem;
      }
    }
  }
  .h5 {
    width: 100%;
    height: 1.26rem;
    line-height: 1.26rem;
    font-size: 0.34rem;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.8);
    text-align: center;
    border-top: 0.02rem solid rgba(0, 0, 0, 0.1);
    margin-top: 0.5rem;
  }
}
</style>
